<template>
  <div class="admin-profile">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人信息管理</span>
          <el-button type="primary" @click="handleEdit">编辑资料</el-button>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="avatar-container">
            <el-avatar :size="120" :src="userInfo.avatar || defaultAvatar"></el-avatar>
            <el-upload
              v-if="isEditing"
              class="avatar-uploader"
              action="/api/api/admin/profile/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary" class="update-btn">更换头像</el-button>
            </el-upload>
          </div>
        </el-col>
        
        <el-col :span="18">
          <el-form 
            ref="profileForm"
            :model="userInfo"
            :disabled="!isEditing"
            label-width="100px"
            :rules="rules"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userInfo.username" placeholder="请输入用户名" />
            </el-form-item>
            
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userInfo.realName" placeholder="请输入真实姓名" />
            </el-form-item>
            
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userInfo.phone" placeholder="请输入手机号码" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-form-item label="部门" prop="department">
              <el-input v-model="userInfo.department" placeholder="请输入所在部门" />
            </el-form-item>
            
            <el-form-item label="职位" prop="position">
              <el-input v-model="userInfo.position" placeholder="请输入职位" />
            </el-form-item>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="userInfo.bio"
                type="textarea"
                :rows="3"
                placeholder="请输入个人简介"
              />
            </el-form-item>
            
            <el-form-item v-if="isEditing">
              <el-button type="primary" @click="submitForm">保存修改</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    
    <el-card class="login-info-card">
      <template #header>
        <div class="card-header">
          <span>登录信息</span>
        </div>
      </template>
      
      <el-descriptions :column="1" border>
        <el-descriptions-item label="上次登录时间">{{ userInfo.lastLoginTime || '暂无记录' }}</el-descriptions-item>
        <el-descriptions-item label="上次登录IP">{{ userInfo.lastLoginIp || '暂无记录' }}</el-descriptions-item>
        <el-descriptions-item label="上次登录地点">{{ userInfo.lastLoginLocation || '暂无记录' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getAdminProfile, updateAdminProfile } from '@/api/admin'

export default {
  name: 'AdminProfile',
  setup() {
    const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    const profileForm = ref(null)
    const isEditing = ref(false)
    
    const userInfo = reactive({
      username: '',
      realName: '',
      phone: '',
      email: '',
      department: '',
      position: '',
      bio: '',
      avatar: '',
      lastLoginTime: '',
      lastLoginIp: '',
      lastLoginLocation: ''
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }
    
    const fetchUserInfo = async () => {
      try {
        const { data } = await getAdminProfile()
        Object.assign(userInfo, data)
      } catch (error) {
        ElMessage.error('获取个人信息失败')
      }
    }
    
    const handleEdit = () => {
      isEditing.value = true
    }
    
    const cancelEdit = () => {
      isEditing.value = false
      fetchUserInfo() // 重新获取数据，放弃修改
    }
    
    const submitForm = () => {
      profileForm.value.validate(async (valid) => {
        if (valid) {
          try {
            await updateAdminProfile(userInfo)
            isEditing.value = false
            ElMessage.success('个人信息更新成功')
          } catch (error) {
            ElMessage.error('更新个人信息失败')
          }
        } else {
          return false
        }
      })
    }
    
    const handleAvatarSuccess = (res) => {
      // 头像上传成功的回调
      userInfo.avatar = res.data.url
      ElMessage.success('头像上传成功')
    }
    
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
    
    onMounted(() => {
      fetchUserInfo()
    })
    
    return {
      profileForm,
      userInfo,
      isEditing,
      rules,
      defaultAvatar,
      handleEdit,
      cancelEdit,
      submitForm,
      handleAvatarSuccess,
      beforeAvatarUpload
    }
  }
}
</script>

<style scoped>
.admin-profile {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.update-btn {
  margin-top: 15px;
}

.login-info-card {
  margin-top: 20px;
}
</style> 